package problem145;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

//145.二叉树前序遍历 - 非递归
//https://leetcode.cn/problems/binary-tree-postorder-traversal/

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();
            if (top.right == null || top.right == prev) {
                list.add(top.val);
                prev = stack.pop();
            } else {
                cur = top.right;
            }
        }
        return list;
    }
}